package com.example.zookeeper.zookeeper.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ConfigCenter {
    private final static String CONNECT_STR = "localhost:2181";
    private final static Integer SESSION_TIMEOUT = 30 * 1000;
    private static ZooKeeper zooKeeper = null;
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        zooKeeper = new ZooKeeper(CONNECT_STR, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                if (watchedEvent.getType() == Event.EventType.None && watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                    log.info("链接已建立");
                    countDownLatch.countDown();
                }
            }
        });
        countDownLatch.await();
        MyConfig myConfig = new MyConfig();
        myConfig.setKey("123");
        myConfig.setName("Xzy");
//        myConfig.setName("Xzy1");
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = objectMapper.writeValueAsBytes(myConfig);
        zooKeeper.create("/MyConfig1", bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

//        zooKeeper.setData("/MyConfig1",bytes,2);
        val watcher = new Watcher() {
            @SneakyThrows
            @Override
            public void process(WatchedEvent watchedEvent) {
                if (watchedEvent.getType() == Event.EventType.NodeDataChanged && watchedEvent.getPath() != null && watchedEvent.getPath().equals("/MyConfig1")) {
                    log.info("PATH:{} 发生了数据变化", watchedEvent.getPath());
                    byte[] data = zooKeeper.getData("/MyConfig1", this, null);
                    MyConfig newMyConfig1=objectMapper.readValue(new String(data), MyConfig.class);
                    log.info("PATH:{} 发生了数据变化", newMyConfig1);
                }
            }
        };
        byte[] data = zooKeeper.getData("/MyConfig1", watcher, null);
        MyConfig oldMyConfig1=objectMapper.readValue(new String(data), MyConfig.class);
        log.info("PATH:{} 原始数据", oldMyConfig1);

        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
    }
}
